package com.tally.business.mq;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: sy
 * @Date: 2021/2/3 19:00
 * @Description:
 */
@Component
public class MqProducer {
    private Logger logger = LoggerFactory.getLogger(MqProducer.class);

    private DefaultMQProducer producer;

    @Value(value = "${mq.nameserver.addr}")
    private String nameAddr;
    @Value(value = "${mq.topicname}")
    private String topicName;

    @PostConstruct
    public void init() throws MQClientException {
        //做mqproducer初始化
        producer = new DefaultMQProducer("mq_producer_group");
        producer.setNamesrvAddr(nameAddr);
        producer.start();
    }

    public void addExp(Integer userId, String type){
        Map<String,Object> bodyMap = new HashMap<>();
        bodyMap.put("userId",userId);
        bodyMap.put("type",type);
        Message message = new Message(topicName,"addExp", JSON.toJSONBytes(bodyMap));
        try {
            producer.send(message);
            logger.info("加经验请求已发出：userId={},type={}",userId,type);
        } catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
